package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserExample;
import org.linlinjava.litemall.db.domain.UserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class LitemallUserService {
    @Resource
    LitemallUserMapper userMapper;

    public List<LitemallUser> queryByExample(String username,String mobile,Integer page,Integer size,String sort,String order){
        LitemallUserExample example = new LitemallUserExample();
        LitemallUserExample.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(username)){
            criteria.andUsernameLike("%"+username+"%");
        }
        if(!StringUtils.isEmpty(mobile)){
            criteria.andMobileLike("%"+mobile+"%");
        }
        criteria.andDeletedEqualTo(false);
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            example.setOrderByClause(sort+" "+order);
        }
        PageHelper.startPage(page,size);
        return userMapper.selectByExample(example);
    }

    public LitemallUser findById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    public UserVo findUserVoById(Integer userId) {
        LitemallUser user = findById(userId);
        UserVo userVo = new UserVo();
        userVo.setNickname(user.getNickname());
        userVo.setAvatar(user.getAvatar());
        return userVo;
    }

    /**
     * 查询总用户数
     */
    public int count(){
        LitemallUserExample userExample=new LitemallUserExample();
        userExample.or().andDeletedEqualTo(false);

        return (int)userMapper.countByExample(userExample);
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    public List<LitemallUser> queryByUsername(String username){
        LitemallUserExample example = new LitemallUserExample();
        example.or().andUsernameEqualTo(username).andDeletedEqualTo(false);
        return userMapper.selectByExample(example);
    }

    /**
     * 根据id更新用户
     */
    public int updateById(LitemallUser user){
        user.setUpdateTime(new Date());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public void add(LitemallUser user){
        user.setAddTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertSelective(user);
    }

    public List<LitemallUser> queryByMobile(String mobile){
        LitemallUserExample example = new LitemallUserExample();
        example.or().andMobileEqualTo(mobile).andDeletedEqualTo(false);
        return userMapper.selectByExample(example);
    }
}
